package cn.virens.common.easyexcel.converter;

import cn.idev.excel.converters.Converter;
import cn.idev.excel.converters.ReadConverterContext;
import cn.idev.excel.converters.WriteConverterContext;
import cn.idev.excel.metadata.data.FormulaData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.virens.common.util.exception.APIException;
import org.dromara.hutool.core.convert.ConvertUtil;
import org.dromara.hutool.core.text.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExcelDoubleToString implements Converter<Double> {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<Double> context) throws Exception {
        if (context != null && context.getContentProperty() != null && context.getValue() != null) {
            return new WriteCellData<>(Double.toString(context.getValue()));
        }

        return new WriteCellData<>(StrUtil.EMPTY);
    }

    @Override
    public Double convertToJavaData(ReadConverterContext<?> ctx) throws APIException {
        if (ctx != null && ctx.getReadCellData().getStringValue() != null) {
            return pares(ctx.getReadCellData().getStringValue());
        }
        if (ctx != null && ctx.getReadCellData().getNumberValue() != null) {
            return pares(ctx.getReadCellData().getNumberValue());
        }
        if (ctx != null && ctx.getReadCellData().getFormulaData() != null) {
            return pares(ctx.getReadCellData().getFormulaData());
        }
        if (ctx != null && ctx.getReadCellData().getData() != null) {
            return pares(ctx.getReadCellData().getData());
        }

        return null;
    }

    private Double pares(Object data) throws APIException {
        if (data instanceof FormulaData formulaData) {
            data = formulaData.getFormulaValue();
        }

        String value1 = StrUtil.toString(data);
        String value2 = StrUtil.trim(value1);

        return ConvertUtil.toDouble(value2);
    }
}
